package com.tplentiful.log.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import lombok.Data;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.net.PasswordAuthentication;

/**
 * @Author: tplentiful
 * @Since: 1.0
 **/
@Configuration
public class EsConfig {

    @Bean
    public ElasticsearchClient elasticsearchClient(EsConfig.EsProperties properties) {
        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(properties.username, properties.password));
        RestClient restClient = RestClient.builder(
                new HttpHost(properties.host, properties.port)).setHttpClientConfigCallback(o -> {
                    o.disableAuthCaching();
                    return o.setDefaultCredentialsProvider(basicCredentialsProvider);
        }).build();
        ElasticsearchTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }

    @Data
    @Component
    @ConfigurationProperties(prefix = "elasticsearch")
    public static class EsProperties {
        private String host;
        private Integer port;
        private String username;
        private String password;
    }
}
